package com.dtz.rabbitmq.workqueuen.fair;

import java.io.IOException;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

public class Consumer1 {

	public static void main(String[] args) {
		// 1、创建连接工厂
				ConnectionFactory factory = new ConnectionFactory();
				factory.setVirtualHost("/");
				factory.setHost("1.15.137.13");
				factory.setPort(5672);
				factory.setUsername("admin");
				factory.setPassword("admin");
				
				Connection connection = null;
				Channel channel = null;
				
				try {
					
					connection = factory.newConnection();
					
					channel = connection.createChannel();
					
					// 接收消息, 公平分发，关闭自动应答
					final Channel fChannel = channel;
					channel.basicQos(1);
					channel.basicConsume("WF-queuen1", false, new DeliverCallback() {
						
						@Override
						public void handle(String consumerTag, Delivery message) throws IOException {
							System.out.println("work01获得消息：" + new String(message.getBody(), "utf-8"));
							try {
								Thread.sleep(200);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							fChannel.basicAck(message.getEnvelope().getDeliveryTag(), false);
						}
					}, new CancelCallback() {
						
						@Override
						public void handle(String consumerTag) throws IOException {
							System.out.println("获得消息失败");
						}
					});
					
					 System.out.println("Work01-开始接受消息");
			         System.in.read();
					
				} catch (Exception e) {
					// TODO: handle exception
				} finally
				{
					// 9: 释放连接关闭通道
		            if (channel != null && channel.isOpen()) {
		                try {
		                    channel.close();
		                } catch (Exception ex) {
		                    ex.printStackTrace();
		                }
		            }
		            if (connection != null) {
		                try {
		                    connection.close();
		                } catch (Exception ex) {
		                    ex.printStackTrace();
		                }
		            }
				}
	}
	
}
